﻿using System;
using System.Collections.Generic;
 
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;

namespace MapReduce.Services
{
    public abstract class ExecuteJobService : IService
    {
        public abstract byte[][] InnerExecute(Object pJobObj, byte[][] pData);

        public byte[][] Execute(byte[][] pData)
        {
            
            byte[] assemblyArr = pData[0];
            String assemblyName = U.Convert(pData[1]).ToString();
            String className = U.Convert(pData[2]).ToString();


            //Save assembly
            String tmpDir = U.MapPath("Temp");
            if (!Directory.Exists(tmpDir)) Directory.CreateDirectory(tmpDir);

            assemblyName = Path.Combine(tmpDir, Guid.NewGuid().ToString() + assemblyName);

            File.WriteAllBytes(assemblyName, assemblyArr);

            Assembly asm = Assembly.LoadFrom(assemblyName);
            Object jobObj = asm.CreateInstance(className);

            byte[][] returnData = InnerExecute(jobObj, pData);

            try
            {
                File.Delete(assemblyName);
            }
            catch { }

            return returnData;

        }//Execute
    }


}
